package com.leo.customer.manager.impl

import com.alibaba.fastjson.JSON
import com.leo.customer.Constants
import com.leo.customer.manager.RedisManager
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Service
import java.util.concurrent.TimeUnit

@Service
class RedisManagerImpl : RedisManager {

    @Autowired
    lateinit var redisTemplate: RedisTemplate<Any, Any>
    /**
     *
     * 存储对象
     */
    override fun setObj(key: String, obj: Any, timeOut: Long) {
        redisTemplate.boundValueOps(key).set(JSON.toJSONString(obj), timeOut, TimeUnit.SECONDS)
    }

    /**
     * 存储字符串
     */
    override fun setString(key: String, obj: String, timeOut: Long) {
        redisTemplate.boundValueOps(key).set(obj, timeOut, TimeUnit.SECONDS)
    }

    /**
     * 存储Token
     */
    override fun setToken(key: String, obj: Any) {
        setObj("Token_$key", obj, Constants.Token_Expire_Time)
    }

    /**
     * 通过Key获取对象
     */
    override fun <T> getObj(key: String, clazz: Class<T>): T? {
        if (!exists(key)){
            return null
        }
        val json:String = redisTemplate.opsForValue().get(key) as String
        return JSON.parseObject(json, clazz);
    }

    /**
     * 通过Key获取字符串
     */
    override fun getString(key: String): String {
        if (!exists("Token_$key")){
            return ""
        }
        return redisTemplate.opsForValue().get(key) as String
    }

    /**
     * 获取Token存储的对象
     */
    override fun <T> getObjByToken(key: String, clazz: Class<T>): T? {
        if (!exists("Token_$key")){
            return null
        }
        val json = redisTemplate.opsForValue().get("Token_$key") as String
        return JSON.parseObject(json, clazz)
    }

    /**
     * 判断Key是否存在 或者过期
     */
    override fun exists(key: String): Boolean {
        return redisTemplate.hasKey(key)
    }


}
